package com.yuexiao.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.yuexiao.pojo.Employee;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName:UserDetailsService
 * @Auther: YUEXIAO
 * @Description: 自定义用户登录权限
 * @Date: 2022/8/10 17:38
 * @Version: v1.0
 */
@Service("detailsService")
public class DetailsService implements UserDetailsService {

    @Reference
    private EmployeeService employeeService;

    @Override
    public UserDetails loadUserByUsername(String s) {

        //根据传入的员工username查询员工信息
        Employee employeeByUsername = employeeService.getEmployeeByUsername(s);
        //如果该用户不存在则抛出异常，该异常将被失败Handler所接收并处理
        if (employeeByUsername == null) {
            throw new BadCredentialsException("用户名不存在");
        }
        if(employeeByUsername.getStatus()==0){
            throw new BadCredentialsException("该账户已被禁用");
        }
        //将用户所具有权限存入权限集合
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(employeeByUsername.getRole());
        //返回security自带的User对象
        return new User(employeeByUsername.getUsername(), employeeByUsername.getPassword(), authorities);
    }
}
